package org.minbox.framework.command.execute.maven.plugin;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Execute;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.minbox.framework.command.execute.CommandLine;
import org.minbox.framework.command.execute.OperatingSystem;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * Command execute mojo
 *
 * @author 恒宇少年
 */
@Mojo(name = "execute", threadSafe = true, defaultPhase = LifecyclePhase.COMPILE)
@Execute(phase = LifecyclePhase.COMPILE)
public class CommandExecuteMojo extends AbstractMojo {
    /**
     * Whether to skip this execution
     */
    @Parameter(defaultValue = "false")
    private boolean skip;
    /**
     * Execute command line
     */
    @Parameter(required = true)
    private String executable;
    /**
     * Execute command arguments
     */
    @Parameter
    private List<?> arguments;
    /**
     * The project base dir
     */
    @Parameter(readonly = true, required = true, defaultValue = "${basedir}")
    private File basedir;
    /**
     * Build directory
     */
    @Parameter(readonly = true, required = true, defaultValue = "${project.build.directory}")
    private File buildDirectory;
    /**
     * Whether to execute asynchronously
     */
    @Parameter(defaultValue = "false")
    private boolean async;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        if (skip) {
            getLog().info("skip this command line execution");
            return;
        }
        if (async) {
            new Thread(() -> doExecute()).start();
        } else {
            doExecute();
        }
    }

    /**
     * Execute command
     */
    private void doExecute() {
        CommandLine commandLine = CommandLine.instance().setCommand(executable);
        if (arguments != null && arguments.size() > 0) {
            commandLine.addArgs(arguments.toArray(new String[]{}));
        }
        commandLine.execute();
        getLog().info("Command 「" + executable + "」 is executing...");
        String resultContent = commandLine.getResultContent();
        if (resultContent != null && resultContent.length() > 0) {
            getLog().info("Command Execute Result：\n" + resultContent);
        }
        String errorContent = commandLine.getErrorContent();
        if (errorContent != null && errorContent.length() > 0) {
            getLog().info("Command Execute Error：\n" + errorContent);
        }
    }
}
